/*
 * Digital Audio Mobile - A multi track studio for Windows Mobile
 * Copyright (C) 2008 David Olsson
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "AudioBuffer.h"
#include "OutputDevice.h"

using namespace std;

OutputDevice::OutputDevice(UINT index, const WAVEFORMATEX &format) throw(): Device(format), m_hWave(0), m_isPlaying(false), m_buffersInQueue(0) {
    WNDCLASS wc;
    if(!GetClassInfo(GetModuleHandle(0), MSGWNDCLASS, &wc)) {
        ZeroMemory(&wc, sizeof(WNDCLASS));
        wc.lpfnWndProc = msgWndProc;
        wc.hInstance = GetModuleHandle(0);
        wc.lpszClassName = MSGWNDCLASS;
        RegisterClass(&wc);
    }
    m_hMsgWnd = CreateWindow(MSGWNDCLASS, 0, WS_DISABLED | WS_POPUP, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), this);

    waveOutOpen(&m_hWave, index, &format, DWORD(m_hMsgWnd), DWORD(this), CALLBACK_WINDOW);
}

OutputDevice::~OutputDevice() {
    if(isPlaying()) {
        stop();
    }

    DestroyWindow(m_hMsgWnd);
    waveOutClose(m_hWave);
}

void OutputDevice::enqueueBuffer(const AudioBuffer *buffer) throw() {
    WAVEHDR *header = new WAVEHDR();
    header->lpData = LPSTR(buffer->buffer());
    header->dwBufferLength = buffer->bufferSize();
    header->dwUser = DWORD(buffer);
    waveOutPrepareHeader(m_hWave, header, sizeof(WAVEHDR));
    m_headers.push_back(header);
}

void OutputDevice::play() throw() {
    ASSERT(m_buffersInQueue == 0);

    if(!m_headers.empty()) {
        m_isPlaying = true;
        for(list<BufferHandler *>::iterator iter = m_handlers.begin(); iter != m_handlers.end(); iter++) {
            (*iter)->started(this);
        }

        while(!m_headers.empty() && m_buffersInQueue < MAXBUFFERSINQUEUE) {
            WAVEHDR *header = m_headers.front();
            waveOutWrite(m_hWave, header, sizeof(WAVEHDR));
            m_headers.pop_front();
            m_buffersInQueue += 1;
        }
    }
}

void OutputDevice::stop() throw() {
    m_isPlaying = false;
    waveOutReset(m_hWave);

    for(list<WAVEHDR *>::iterator iter = m_headers.begin(); iter != m_headers.end(); iter++) {
        waveOutUnprepareHeader(m_hWave, *iter, sizeof(WAVEHDR));
        delete(*iter);
    }
    m_headers.clear();

    for(list<BufferHandler *>::iterator iter = m_handlers.begin(); iter != m_handlers.end(); iter++) {
        (*iter)->stopped(this);
    }
}

bool OutputDevice::isPlaying() const throw() {
    return(m_isPlaying);
}

LRESULT CALLBACK OutputDevice::msgWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) throw() {
    if(uMsg == WM_CREATE) {
        CREATESTRUCT *cs = reinterpret_cast<CREATESTRUCT *>(lParam);
        SetWindowLong(hWnd, GWL_USERDATA, LONG(cs->lpCreateParams));

        return(0);
    }
    else {
        OutputDevice *dev = reinterpret_cast<OutputDevice *>(GetWindowLong(hWnd, GWL_USERDATA));
        if(dev != 0) {
            switch(uMsg) {
                case MM_WOM_DONE:{
                    WAVEHDR *header = reinterpret_cast<WAVEHDR *>(lParam);
                    waveOutUnprepareHeader(dev->m_hWave, header, sizeof(WAVEHDR));
                    dev->m_buffersInQueue -= 1;
                    if(dev->m_isPlaying) {
                        for(list<BufferHandler *>::iterator iter = dev->m_handlers.begin(); iter != dev->m_handlers.end(); iter++) {
                            (*iter)->bufferCompleted(dev, reinterpret_cast<const AudioBuffer *>(header->dwUser));
                        }
                    }
                    delete(header);

                    if(dev->m_isPlaying) {
                        if(dev->m_headers.empty()) {
                            if(dev->m_buffersInQueue == 0) {
                                dev->m_isPlaying = false;
                                for(list<BufferHandler *>::iterator iter = dev->m_handlers.begin(); iter != dev->m_handlers.end(); iter++) {
                                    (*iter)->stopped(dev);
                                }
                            }
                        }
                        else {
                            while(!dev->m_headers.empty() && dev->m_buffersInQueue < MAXBUFFERSINQUEUE) {
                                WAVEHDR *header = dev->m_headers.front();
                                waveOutWrite(dev->m_hWave, header, sizeof(WAVEHDR));
                                dev->m_headers.pop_front();
                                dev->m_buffersInQueue += 1;
                            }
                        }
                    }

                    return(0);
                }
                default:
                    return(DefWindowProc(hWnd, uMsg, wParam, lParam));
            }
        }
        else {
            return(DefWindowProc(hWnd, uMsg, wParam, lParam));
        }
    }
}

const TCHAR * const OutputDevice::MSGWNDCLASS = TEXT("DamOutputDeviceMsgWndClass");
const unsigned int OutputDevice::MAXBUFFERSINQUEUE = 2;
